/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DBHandling;

import Utilities.Encrypt;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.swing.JOptionPane;

/**
 *
 * @author NguyenPhuThien
 */
public class LoginHandling {

    DBUtil objDB = new DBUtil();
    ResultSet rsUser;
    ResultSet rsRole;

    public LoginHandling() {
        objDB.connect();
    }

    public boolean checkLogin(String username, String password, String role) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, FileNotFoundException, IOException, NoSuchAlgorithmException {
        String encryptedPassword = Encrypt.encryptMD5(password);
        try {
            boolean success = false;
            rsUser = objDB.executeSQL("SELECT passwd,roleID FROM Staffs WHERE username='" + username + "'");
            if (rsUser.wasNull()) {
                success = false;
                return success;
            } else {
                rsUser.last();
                String dbPassword = rsUser.getString("passwd");
                String inputRoleName = rsUser.getString("roleID");
                rsRole = objDB.executeSQL("SELECT roleName FROM Roles WHERE roleID='" + inputRoleName + "'");
                rsRole.last();
                String dbRoleName = rsRole.getString("roleName");
                if (dbPassword.toLowerCase().equals(encryptedPassword)) {
                    if (dbRoleName.equals(role)) {
                        success = true;
                        return success;
                    } else {
                        JOptionPane.showMessageDialog(null, "The permission is not match!", "Notice", JOptionPane.WARNING_MESSAGE);
                        success = false;
                        return success;
                    }
                } else {
                    
                    JOptionPane.showMessageDialog(null, "The password does not match!", "Notice", JOptionPane.WARNING_MESSAGE);
                    success = false;
                    return success;
                }
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "The user does not exist!", "Notice", JOptionPane.WARNING_MESSAGE);
            return false;
        } finally {
            try {
                objDB.closeConnection();
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage(), "Warning", JOptionPane.WARNING_MESSAGE);
            }
        }
            
        
    }
}
